#include "ComponentsDlg.h"
#include "ConnectionString.h"
#include "Comtools.h"

#include <QMessageBox>
#include <QItemSelectionModel>
#include <QFileDialog>
#include <sstream>

#import "msado15.dll" rename_namespace("ADODB") rename("EOF", "ADOEOF")  


void ComponentsDlg::getComponents()
{
  try {
    CoInitialize(NULL);
    HRESULT hr;
    int row = 0;
    
    this->tableWidgetComponents->clearContents();
    this->tableWidgetComponents->setRowCount(0);
    this->tableWidgetComponents->setSelectionMode(QAbstractItemView::SingleSelection);
    this->tableWidgetComponents->setSelectionBehavior(QAbstractItemView::SelectRows);
    
    _bstr_t sql =  " select * from component_register order by registration_time, last_activity desc ";

    ADODB::_ConnectionPtr c; 
    hr = c.CreateInstance(__uuidof(ADODB::Connection), NULL, CLSCTX_INPROC_SERVER);  
    if (S_OK != hr) throw("CreateInstance failed");
    hr = c->Open(bstr_t(CONNECTSTRING), L"", L"", -1);  

    ADODB::_RecordsetPtr rs;  
    rs.CreateInstance (__uuidof(ADODB::Recordset));  
    rs->Open(sql, c.GetInterfacePtr(), ADODB::adOpenStatic, ADODB::adLockOptimistic, ADODB::adCmdText);  

    if (!rs->ADOEOF) hr = rs->MoveFirst();
    if (S_OK == hr) {
      this->tableWidgetComponents->setRowCount(rs->RecordCount);
      while (S_OK == hr && !rs->ADOEOF) {          
        _bstr_t type = rs->Fields->GetItem(L"component_type")->GetValue();
        _bstr_t subject = rs->Fields->GetItem(L"subject")->GetValue();
        _bstr_t guid = rs->Fields->GetItem(L"component_guid")->GetValue();
        _bstr_t registered = rs->Fields->GetItem(L"registration_time")->GetValue();
        _bstr_t redundant = rs->Fields->GetItem(L"enable_redundancy")->GetValue();
        _bstr_t master = rs->Fields->GetItem(L"master")->GetValue();

        this->tableWidgetComponents->setItem(row, 0, new QTableWidgetItem((char*)type));
        this->tableWidgetComponents->setItem(row, 1, new QTableWidgetItem((char*)subject));
        this->tableWidgetComponents->setItem(row, 2, new QTableWidgetItem((char*)guid));
        this->tableWidgetComponents->setItem(row, 3, new QTableWidgetItem((char*)registered));
        this->tableWidgetComponents->setItem(row, 4, new QTableWidgetItem((char*)redundant));
        this->tableWidgetComponents->setItem(row, 5, new QTableWidgetItem((char*)master));

        row++;
        hr = rs->MoveNext();
      }
    }
    try { rs->Close(); } catch (...) {}
    try { c->Close(); } catch (...) {}
  } catch (_com_error& e) {
    BSTR b;
    if (e.ErrorInfo()) {
      e.ErrorInfo()->GetDescription(&b);
      char szErr[256];
      sprintf(szErr, "Error: %s\n",_com_util::ConvertBSTRToString(b));
      OutputDebugString(szErr);
    }
  } catch (...) {
  }
}

void ComponentsDlg::clickClose()
{
  close();
}